/**************************************************************************//**
 * @file           main.c
 * @version        V1.0
 * $Revision:      1 $
 * $Date:          2017/01/04 $
 * @brief          Main function
 * @Author         Jeffrey Kang
 * @ContactInfo    chkang@esmt.com.tw
 *
 * @note
 *
 * Copyright (C) 1998 Elite Semiconductor Memory Technology Corp.
 * All rights reserved.
 *
 ******************************************************************************/


#include <REG52.h>
#include "system_FE81001.h"


#define WRITE_PROTECT      0xA5
#define MAGIC_NUM          0x5A


volatile unsigned char cnt = 0;


/**
 * @brief       delay function
 *
 * @param       None
 *
 * @return      None
 *
 * @details     1. 
 */
void delay (int cnt )
{
	unsigned int i , j ;
	
	for(j=0 ; j<cnt ; j++)
	for( i = 0 ; i < 200 ; i++ ); 
	
}


/**
 * @brief       TCKISR function
 *
 * @param       None
 *
 * @return      None
 *
 * @details     1. 
 */
const void WDTISR (void) interrupt ISR_WDT
{
	/* clear interrupt flag */
	unsigned char int_stat = WDT->status;
	WDT->status = 0x01;

	/* Restart WDT */
	//WDT_Reset();
	
	/* enable global interrupt */
	INTC->int_gmask = 0x01;
}


/**
 * @brief       WDTInit function
 *
 * @param       None
 *
 * @return      None
 *
 * @details     1. 
 */
void WDTInit(void)
{
	/* Enable DT write protect */
	En_WDT_WriteProtect();

	/* Set Reset Time */
	Reset_Time_Period_x1024();  // Period = 1/32768  i.e. Interrupt time  = 0.03125s
	
	/* Set Interrupt Time */
	Interrupt_Time_Period_x32768(); // Period = 1/32768  i.e. Interrupt time  = 1s
	
	/* WDT Enable */
	WDT_Reset_Enable();
	WDT_INTEN_Enable();
	WDT_WDTEN_Enable();
}


/**
 * @brief       WDTClkInit function
 *
 * @param       None
 *
 * @return      None
 *
 * @details     1. 
 */
void WDTClkInit (void)
{
	/* enable LSRC clock */
	LSRCEN_Enable();          

	/* Select LSRC clock */
	WDT_Set_clock_LSRC();
	
	/* wait LSRC stable */
	while((CLKC->clkstb & 0x04)!= 0x04){}
	
	/* enable WDT clock */
	En_WDT_clk();
}


/**
 * @brief       main function
 *
 * @param       None
 *
 * @return      None
 *
 * @details     1. 
 */
int main( void )
{
	/* Enable PA PB PC PD Clock */
  PORT_PAPBPCPD_Clock_Enable();
	
	/* Set PC7 input as button */
	PORT_SetPCInput(BIT7);

	/* Set PD1. ,PD2.,PD3 output */
	PORT_SetPDPushPull(BIT1 | BIT2 | BIT3 );
	
	/* Toggle  LED when WDT happen */
	PD1 =0;
	PD2 =0;
	PD3 =0;
	delay(500);

	PD1 =1;
	PD2 =1;
	PD3 =1;
	delay(500);

	/* enable WDT clock */
	WDTClkInit();
	
	/* WDT init */
	WDTInit();
	
	/* enable global interrupt */
	INTC->int_gmask = 0x01;
	
	while(1)
	{
		// Reset WDT in Interrupt 
	}
}
